package com.youxue.controller;

import com.alibaba.fastjson.JSONObject;
import com.cangshi.permission.entity.UserSubject;
import com.youxue.entity.*;
import com.youxue.permission.saver.SubjectHolder;
import com.youxue.service.ClassService;
import com.youxue.service.OrderService;
import com.youxue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 15c on 2018/1/26.
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;

    /**
     * 生成新订单（默认订单状态为未支付=1，支付后将为0）
     *
     * @param classId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String addAOrder(@RequestParam(required = false) Integer classId) {

        ErrorJsonObject errorJsonObject;
        if (null == classId) {
            errorJsonObject = new ErrorJsonObject(100, "classId参数为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        //查询是否已经存在该订单
        Order orderResult = orderService.showAOrderInfo(userId, classId);
        if (orderResult != null) {
            //查看该用户是否已经购买此课程
            if (0 == orderResult.getOrderStatus() || 2 == orderResult.getOrderStatus()) {
                errorJsonObject = new ErrorJsonObject(101, "该课程已购买，请勿重复购买");
                return JSONObject.toJSONString(errorJsonObject);
            }
            errorJsonObject = new ErrorJsonObject(102, "已存在该订单，勿重复生成，去订单中心查看");
            return JSONObject.toJSONString(errorJsonObject);
        }
        Order order = new Order();
        order.setOrderUserId(userId);
        order.setOrderClassId(classId);
        String orderNum;

        //获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        String date = sdf.format(new java.util.Date());


        //设置订单号为当前时间加随机数加用户id
        orderNum = date + userId;
        order.setOrderNum(orderNum);
        int result = orderService.addOrder(order);
        if (1 == result) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("生成订单成功");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            errorJsonObject = new ErrorJsonObject(103, "订单生成失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 用户删除一个订单
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String deleteAOrder(@RequestParam(required = false) Integer orderId) {
        ErrorJsonObject errorJsonObject;
        if (null == orderId) {
            errorJsonObject = new ErrorJsonObject(104, "欲删除orderId为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        Order order = orderService.showAOldOrderInfo(orderId);
        if (order.getOrderStatus() == 0) {
            //将orderStatus改为2，表示已支付却删除的订单
            int re = orderService.reviseOrderStatus(orderId);
            if (1 == re) {
                CorrectJsonObject correctJsonObject = new CorrectJsonObject("订单删除成功");
                return JSONObject.toJSONString(correctJsonObject);
            } else {
                errorJsonObject = new ErrorJsonObject(105, "订单删除失败");
                return JSONObject.toJSONString(errorJsonObject);
            }
        } else {
            int result = orderService.deleteOrder(orderId);
            if (1 == result) {
                CorrectJsonObject correctJsonObject = new CorrectJsonObject("订单删除成功");
                return JSONObject.toJSONString(correctJsonObject);
            } else {
                errorJsonObject = new ErrorJsonObject(106, "订单删除失败");
                return JSONObject.toJSONString(errorJsonObject);
            }
        }
    }

    /**
     * 查看的登录用户所有订单
     *
     * @param orderStatus 订单状态（1：未支付；0：已支付）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/listorder", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAUserAllOrder(@RequestParam(required = false) Integer orderStatus) {
        ErrorJsonObject errorJsonObject;
        if (null == orderStatus) {
            errorJsonObject = new ErrorJsonObject(107, "orderStatus为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        List<Order> orderList = new ArrayList<Order>();
        orderList = orderService.showAUserAllOrder(userId, orderStatus);
        if (orderList.size() != 0) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(orderList);
            return JSONObject.toJSONString(correctJsonObject);
        } else if (orderList.size() == 0) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功,当前用户还未有任何订单");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            errorJsonObject = new ErrorJsonObject(108, "查询出错，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 查看的登录用户所有订单（支付于未支付都查）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/allorders", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAUserAllOrder() {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        List<Order> orderList = new ArrayList<Order>();
        orderList = orderService.showAUserAllOrders(userId);
        if (orderList.size() != 0) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(orderList);
            return JSONObject.toJSONString(correctJsonObject);
        } else if (orderList.size() == 0) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功,当前用户还未有任何订单");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(116, "查询出错，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }


    /**
     * 展示一个用户以前创建的订单详情
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/orderinfo", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAOldOrderInfo(@RequestParam(required = false) Integer orderId) {
        ErrorJsonObject errorJsonObject;
        if (null == orderId) {
            errorJsonObject = new ErrorJsonObject(109, "orderId为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        Order order = orderService.showAOldOrderInfo(orderId);
        if (null == order) {
            errorJsonObject = new ErrorJsonObject(110, "查询出错，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        } else {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(order);
            return JSONObject.toJSONString(correctJsonObject);
        }
    }

    /**
     * 展示一个用户刚新创建的订单，为用户确认并选择是否马上完成支付该课程使用
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/noworderinfo", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showANowOrderInfo() {
        ErrorJsonObject errorJsonObject;
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        Order order = orderService.showANowOrderInfo(userId);
        if (null == order) {
            errorJsonObject = new ErrorJsonObject(111, "查询出错，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        } else {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(order);
            return JSONObject.toJSONString(correctJsonObject);
        }
    }

    /**
     * 展示一个用户的课程订单(在购物车购买情况下使用)
     * @param classId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/aclassorderinfo", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAClassOrderInfo(@RequestParam(required = false) Integer classId) {
        ErrorJsonObject errorJsonObject;
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        Order order = orderService.showAOrderNo(userId, classId);
        if (null == order) {
            errorJsonObject = new ErrorJsonObject(120, " 查询出错，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        } else {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(order);
            return JSONObject.toJSONString(correctJsonObject);
        }
    }

    @Autowired
    ClassService classService;
    @Autowired
    UserService userService;

    /**
     * 完成一个订单支付
     * 支付失败，数据回滚
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/payorder", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String payAOrder(@RequestParam(required = false) Integer orderId) {
        ErrorJsonObject errorJsonObject;
        if (null == orderId) {
            errorJsonObject = new ErrorJsonObject(112, "orderId为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        //查询该订单的状态
        Order order = orderService.showAOldOrderInfo(orderId);
        if (0 == order.getOrderStatus()) {
            errorJsonObject = new ErrorJsonObject(113, "该订单已经支付，请勿重复支付");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (userId != order.getOrderUserId()) {
            errorJsonObject = new ErrorJsonObject(114, "登录用户与订单用户不同");
            return JSONObject.toJSONString(errorJsonObject);
        }
        com.youxue.entity.Class aclass = classService.showAClassInfo(order.getOrderClassId());
        // 获得课程价格
        double price = aclass.getClassPrice();
        //查询用户余额
        double balance = userService.showAUserBalance(userId);
        if (balance - price < 0) {
            errorJsonObject = new ErrorJsonObject(115, "账户余额不足，请充值");
            return JSONObject.toJSONString(errorJsonObject);
        }
        User user = new User();
        user.setUserId(userId);
        user.setUserBalance(balance - price);
        int result = userService.reviseAUserBalance(user);
        if (1 != result) {
            errorJsonObject = new ErrorJsonObject(116, "支付失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
        try {
            //修改订单状态
            orderService.payAOrder(orderId);
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("订单支付成功");
            return JSONObject.toJSONString(correctJsonObject);
        } catch (Exception e) {
            errorJsonObject = new ErrorJsonObject(117, "订单支付状态修改出错，数据回滚，请重新支付");
            user.setUserId(userId);
            user.setUserBalance(balance);
            userService.reviseAUserBalance(user);
            return JSONObject.toJSONString(errorJsonObject);
        }

    }

    /**
     * 展示一个用户所购买的课程
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/buyclass", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAUserBuyClass() {
        ErrorJsonObject errorJsonObject;
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        List<Order> orderList = orderService.showAUserBuyClass(userId);
        if (orderList.size() == 0) {
            errorJsonObject = new ErrorJsonObject(0, "查询结果为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(orderList);
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 通过orderId删除课程购买记录
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete/buyclass", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String deleteAUserBuyClass(@RequestParam(required = false) Integer orderId) {
        ErrorJsonObject errorJsonObject=null;
        if (null == orderId) {
            errorJsonObject = new ErrorJsonObject(125, "orderId为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        int result=orderService.reviseOrderClassCondition(orderId);
        if(1==result){
            return JSONObject.toJSONString("删除购买记录成功");
        }else {
            errorJsonObject = new ErrorJsonObject(126, "删除购买记录失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }


    /**
     * 完成多个订单支付
     * 支付失败，数据回滚
     *
     * @param orderIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/paysomeorder", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String paySomeOrder(@RequestParam(required = false) String orderIds) {
        ErrorJsonObject errorJsonObject;
        if (null == orderIds || "".equals(orderIds)) {
            errorJsonObject = new ErrorJsonObject(118, "orderIds为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();

        //以‘,’分割scIds
        String[] orderId;
        orderId = orderIds.split(",");
        //课程总价格
        double allPrice = 0;
        //解析的id
        int intId;
        //单个订单执行结果
        int result;
        //总的订单执行结果和
        int allResult = 0;
        Order order = null;
        com.youxue.entity.Class aclass = null;
        for (String id : orderId) {
            intId = Integer.parseInt(id);//[String]待转换的字符串
            order = orderService.showAOldOrderInfo(intId);
            //该订单未支付
            if (1 == order.getOrderStatus()) {
                //查询对应课程对象
                aclass = classService.showAClassInfo(order.getOrderClassId());
                // 累计对应课程价格
                allPrice += aclass.getClassPrice();
            }
        }
        //查询用户余额
        double balance = userService.showAUserBalance(userId);
        if (balance - allPrice < 0) {
            errorJsonObject = new ErrorJsonObject(119, "账户余额不足，请充值");
            return JSONObject.toJSONString(errorJsonObject);
        }
        //修改用户余额
        User user = new User();
        user.setUserId(userId);
        user.setUserBalance(balance - allPrice);
        result = userService.reviseAUserBalance(user);
        if (1 != result) {
            errorJsonObject = new ErrorJsonObject(121, "支付失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
        try {
            for (String id : orderId) {
                intId = Integer.parseInt(id);//[String]待转换的字符串
                //修改订单状态
                result = orderService.payAOrder(intId);
                allResult += result;
            }
            //判断每个订单是否都修改成功
            if (orderId.length == allResult) {
                CorrectJsonObject correctJsonObject = new CorrectJsonObject("订单支付成功");
                return JSONObject.toJSONString(correctJsonObject);
            } else {
                user.setUserId(userId);
                user.setUserBalance(balance);
                userService.reviseAUserBalance(user);
                for (String id : orderId) {
                    intId = Integer.parseInt(id);//[String]待转换的字符串
                    //修改订单状态（全部回滚为待支付1）
                    orderService.payAOrderRollback(intId);
                }
                errorJsonObject = new ErrorJsonObject(122, "订单支付状态修改出错，数据回滚，请重新支付");
                return JSONObject.toJSONString(errorJsonObject);
            }

        } catch (Exception e) {
            errorJsonObject = new ErrorJsonObject(123, "订单支付状态修改出错，数据回滚，请重新支付");
            user.setUserId(userId);
            user.setUserBalance(balance);
            userService.reviseAUserBalance(user);
            for (String id : orderId) {
                intId = Integer.parseInt(id);//[String]待转换的字符串
                //修改订单状态（全部回滚为待支付1）
                orderService.payAOrderRollback(intId);
            }
            return JSONObject.toJSONString(errorJsonObject);
        }
    }
}
